<template>
  <div>
    <a-card>
      <div ref="lineChart1" :style="{width:'100%',height:'368px'}"></div>
      <div ref="lineChart2" v-if="!searchData.studentId" :style="{width:'100%',height:'368px'}"></div>
      <!-- <div ref="lineChart3" :style="{width:'100%',height:'368px'}"></div>
      <div ref="lineChart3" :style="{width:'100%',height:'368px'}"></div> -->
    </a-card>
  </div>
</template>
<script>
import { getAction } from '@/api/manage'

export default
{
  name: 'attendance',
  data() {
    return {
      url: {
        list: 'management/skStudentCheck/getStudentCheckStatistical',
        classList: '/management/skStudentCheck/getClassCheckTotalStatistical',
        stuList: 'management/skStudentCheck/getAllStudentCheckStatistical',
        stuInfoSem: 'management/skStudentCheck/getStudentCheckByMonth',
      },
      searchData: {
        semesterId: '',
        classId: '',
        studentId: '',
      },
      dataList:[],
      numList:[]
    }
  },
  props:["dataForm","semesterName","className"],
  components: {},
  filters: {},
  
  computed: {},
  
  created() {
  },
  
  activated() {
  },

  mounted() {
    this.load()
  },

  methods: {
    // 加载报表
    load() {
      const dataForm = this.dataForm
      this.numList = []
      // 查询列表数据
      this.searchData.semesterId = dataForm.semesterId ? dataForm.semesterId : dataForm.semesterHistoryId
      this.searchData.classId = dataForm.classId ? dataForm.classId : undefined
      this.searchData.studentId = dataForm.studentId ? dataForm.studentId : undefined
      if(dataForm.studentId) {
        this.initStudentChart();
      } else if(dataForm.classId) {
        this.initClassChart();
      } else{
        this.initAllChart();
      }
    },
    // 所有报表
    initAllChart() {
      this.monthChart()
      this.classChart()
    },
    // 每月
    monthChart() {
      const params = {
        statisticalScope: 'all',
        timeScope: this.searchData.semesterId,
      }
      getAction(this.url.list, params).then(res => {
        if(res.success) {
          //全园月平均
          var categorys = [];
          var xData1 = [];
          var xData2 = [];
          const monthColumns = this.dataForm.monthColumns;
          for(let rowIndex = 0; rowIndex < monthColumns.length; rowIndex++){
            const rowString = monthColumns[rowIndex].toString();
            categorys.push(rowString);
            const monthData = res.result.find(item => item.month == rowString);
            if (monthData){
              xData1.push((monthData.rate*100).toFixed(2));
              xData2.push((monthData.lateRate*100).toFixed(2));
            } else {
              xData1.push(0);
              xData2.push(0);
            }
          }
          this.initLineChart(this.$refs.lineChart1, '每月出勤率',categorys, xData1, xData2);
        }
      })
    },
    // 每班
    classChart() {
      const params = {
        statisticalScope: 'class',
        timeScope: this.searchData.semesterId,
      }
      getAction(this.url.classList, params).then(res => {
        if(res.success) {
          // 各班平均
          var categorys = [];
          var xData1 = [];
          var xData2 = [];
          const classList = this.dataForm.classList.filter(item => { return item.id != ''});
          classList.forEach(el => {
            categorys.push(el.className);
            const classData = res.result.find(item => item.classId == el.id);
            if (classData){
              xData1.push((classData.rate*100).toFixed(2));
              xData2.push((classData.lateRate*100).toFixed(2));
            } else {
              xData1.push(0);
              xData2.push(0);
            }
          });
          this.initLineChart(this.$refs.lineChart2, '全班学期出勤率', categorys, xData1, xData2);
        } else {
          this.$message.warning(res.message);
          this.loading = false;
        }
      })
    },
    initClassChart() {
      this.monthClassChart();
      this.classStudentChart();
    },
    monthClassChart() {
      const params = {
        statisticalScope: 'class',
        timeScope: this.searchData.semesterId,
        classId: this.searchData.classId
      }
      getAction(this.url.list, params).then(res => {
        if(res.success) {
          var categorys = [];
          var xData1 = [];
          var xData2 = [];
          const monthColumns = this.dataForm.monthColumns;
          for(let rowIndex = 0; rowIndex < monthColumns.length; rowIndex++){
            const rowString = monthColumns[rowIndex].toString();
            categorys.push(rowString);
            const monthData = res.result.find(item => item.month == rowString);
            if (monthData){
              xData1.push((monthData.rate*100).toFixed(2));
              xData2.push((monthData.lateRate*100).toFixed(2));
            } else {
              xData1.push(0);
              xData2.push(0);
            }
          }
          this.initLineChart(this.$refs.lineChart1, '每月平均出勤率',categorys, xData1, xData2);
        } else {
          this.$message.warning(res.message);
          this.loading = false;
        }
      })
    },
    classStudentChart() {
      const params = {
        statisticalScope: 'student',
        semesterId: this.searchData.semesterId,
        classId: this.searchData.classId
      }
      getAction(this.url.stuList, params).then(res => {
        if(res.success) {
          var categorys = [];
          var xData1 = [];
          var xData2 = [];

          res.result.forEach(student => {
            categorys.push(student.studentName);
            xData1.push((student.rate*100).toFixed(2));
            xData2.push((student.lateRate*100).toFixed(2));
          })
          this.initLineChart(this.$refs.lineChart2, '幼儿学期平均出勤率/迟到率对比',categorys, xData1, xData2);
        } else {
          this.$message.warning(res.message);
          this.loading = false;
        }
      })
    },
    initStudentChart() {
      const params = {
        semesterId: this.searchData.semesterId,
        studentId: this.searchData.studentId,
      }
      getAction(this.url.stuInfoSem, params).then(res => {
        if(res.success) {
          //全园月平均
          var categorys = [];
          var xData1 = [];
          var xData2 = [];
          const monthColumns = this.dataForm.monthColumns;
          for(let rowIndex = 0; rowIndex < monthColumns.length; rowIndex++){
            const rowString = monthColumns[rowIndex].toString();
            categorys.push(rowString);
            const monthData = res.result.find(item => item.month == rowString);
            if (monthData){
              xData1.push((monthData.rate*100).toFixed(2));
              xData2.push((monthData.lateRate*100).toFixed(2));
            } else {
              xData1.push(0);
              xData2.push(0);
            }
          }
          this.initLineChart(this.$refs.lineChart1, '每月平均出勤率',categorys, xData1, xData2);
        }
      })
    },
    initLineChart(el, title, categorys, xData1, xData2) {
      var myChartSports;
      if(this.$echarts.getInstanceByDom(el)) {
        myChartSports = this.$echarts.getInstanceByDom(el)
      }
      else{
        myChartSports = this.$echarts.init(el)
      }

      var legendTitle = ['考勤率(%)', '迟到率(%)'];
      // option
      let optionSports = {
        backgroundColor: '#fff',
        title : {
          show:true,//显示策略，默认值true,可选为：true（显示） | false（隐藏）
          text: this.semesterName + ' ' + this.className + title,//主标题文本，'\n'指定换行
          x:'center',//水平安放位置，默认为'left'，可选为：'center' | 'left' | 'right' | {number}（x坐标，单位px）
	        y:'top',//垂直安放位置，默认为top，可选为：'top' | 'bottom' | 'center' | {number}（y坐标，单位px）
        },
        tooltip: {
          borderColor: 'transparent',
          trigger: 'axis',
          backgroundColor: 'rgba(0,0,0,0.5)',
          axisPointer: {
            type: 'shadow',
            label: {
              show: true,
              backgroundColor: '#333'
            }
          },
          textStyle: {
            align: 'left',
            color: '#fff',
            fontSize: '12'
          }
        },
        legend: {
          data: legendTitle,
          textStyle: {
            color: '#ccc'
          },
          // orient: 'vertical', //垂直显示 
          y: 'top', //延Y轴居中 
          x: 'right', //居右显示
          right: '15%'
        },
        grid: {
          left: '10%',
          top: '15%',
          right: '10%',
          bottom: '10%'
        },
        xAxis: {
          data: categorys,
          axisLine: {
            lineStyle: {
              color: '#666'
            }
          }
        },
        yAxis: [
          {
            // name: legendTitle[0],
            splitLine: {
              show: false
            },
            axisLine: {
              show: true,
              lineStyle: {
                color: '#999'
              }
            },
            nameTextStyle: {
              color: '#999'
            },
            splitArea: {
              show: false
            }
          },
          // {
          //   name: legendTitle[1],
          //   splitLine: {
          //     show: false
          //   },
          //   axisLine: {
          //     show: true,
          //     lineStyle: {
          //       color: '#999'
          //     }
          //   },
          //   nameTextStyle: {
          //     color: '#999'
          //   },
          //   splitArea: {
          //     show: false
          //   }
          // },
        ],
        series: [
          {
            name: legendTitle[0],
            type: 'line',
            smooth: true,
            showAllSymbol: true,
            symbol: 'emptyCircle',
            symbolSize: 8,
            itemStyle: {
              normal: {
                color: '#0BA6E3',
                label : {
                  show: true // 显示数据
                },
              }
            },
            data: xData1
          },
          {
            name: legendTitle[1],
            type: 'line',
            smooth: true,
            showAllSymbol: true,
            symbol: 'emptyCircle',
            symbolSize: 8,
            // yAxisIndex: 1,
            itemStyle: {
              normal: {
                color: '#FFC005',
                label : {
                  show: true // 显示数据
                },
              }
            },
            data: xData2
          },
        ]
      }

      myChartSports.setOption(optionSports);
      setTimeout(() => {
        this.handleEmit()
      }, 3000);
      window.addEventListener("resize", ()=>{
        myChartSports.resize();
      })
    },
    handleEmit(){
      this.numList.push(true);
      if(this.dataForm.studentId) {
        if (this.numList.length == 1) {
          this.$emit("ok")
        }
      }else if(this.dataForm.classId) {
        if (this.numList.length == 2) {
          this.$emit("ok")
        }
      }else{
        if (this.numList.length == 2) {
          this.$emit("ok")
        }
      }
    }
  }
}
</script>
<style scoped lang="less">
</style>